<?php
/*
This php requires the following variables to be set correctly and is meant only for includes and not usable on its own.
    $required = array with string representing required post fields
    $fallback = page to go back to in case of error
    $_GET['id'] -> $id to write. 0 means new
    $site = source page including this php
    $createlevel = level required for inserting a new line
    $editlevel = level required for updating a existing line
    $edit_prep = string for prepared statement describing expected data types in case of update
    $create_prep = string for prepared statement describing expected data types in case of insert
    $table = name of the table to be written.
    $loc_entity = localised nice name for the Entity
    Requires the $table to have a field called 'id' of type int and 'created' of type datetime
*/

$id = 0;
if (isset($_GET['id']))
    $id = $_GET['id'];
if(!isset($required) || count($required) == 0){
    die(sprintf(RLang("err_varaible_not_set_by_site"), '$required', $site));
}

foreach($required as $pfield){
    if( !isset($_POST[$pfield])){
        $_SESSION['msgtype'] = "error";
        $_SESSION['msg'] = sprintf(RLang("err_post_field_missing"), $pfield, $site);
        header("Location: $fallback");
        exit();
    }
}


if ($id == 0){
    if (!validate(LEVEL_CREATE_TASK, $site, $db, $fallback) )
        exit();
    
    $sql = "Insert into $table(";
    $values = "";
    $args = [$db, 0, $create_prep];
    foreach($required as $p){
        $sql = $sql."$p,";
        array_push($args, $_POST[$p]);
        $values = $values."?,";
    }
    $sql = $sql." created) values(".$values." NOW())";
    $args[1] = $sql;
    $result = call_user_func_array("get_db_result",$args);
    //get_db_result($db, $sql, "si", $_POST['name'], $_POST['project_id']);
} else{
    if (!validate(LEVEL_EDIT_PROJECT, $site, $db, $fallback) )
        exit();

    $sql = "Update $table set ";
    
    $args = [$db, 0, $edit_prep];
    $last = $required[count($required) - 1];
    foreach($required as $p){
        if($last == $p)
            $sql = $sql." $p=?";
            else
            $sql = $sql."$p=?,";
        array_push($args, $_POST[$p]);
    }
    $sql = $sql." where id = ?";
    array_push($args, $id);
    $args[1] = $sql;
    $result = call_user_func_array("get_db_result",$args);
    //$result = get_db_result($db, $sql, "sii", $_POST['name'], $_POST['customer_id'],  $id);
}
if (!$result) {
    echo ($sql . " ");
    die(mysqli_error($db));
}else{
    $_SESSION['msgtype'] = "msg";
    $_SESSION['msg'] = sptringf(RLang("msg_save_success"), $loc_entity);
    header("Location: $fallback");
    exit();
}
